package com.lhd._05mvcboot02.controller;


import com.lhd._05mvcboot02.conmmon.response.JsonResult;
import com.lhd._05mvcboot02.mapper.UserMapper;
import com.lhd._05mvcboot02.pojo.dto.AddUserDTO;
import com.lhd._05mvcboot02.pojo.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author lhd
 * @date 2024/4/22
 * @apiNote
 */
/**
 * RestController注解:
 *   1.组合注解:相当于 Controller + ResponseBody;
 *   2.在控制器类上添加此注解后,所有的控制器方法上都无需再添加 @ResponseBody 注解了.
 */
@Api(tags = "用户模块" )
@Slf4j
@RestController
@RequestMapping(value = "/v1/users/")
public class UserController {

    @Autowired
    UserMapper userMapper;
    /**
     * 1.添加用户
     */
    @PostMapping(value = "insert")
    @ApiOperation("添加用户")
    public JsonResult addUser(AddUserDTO addUserDTO){
        /*
            梳理业务逻辑,确定接口,以注册功能为例:
            1.接收客户端传递过来的数据;
            2.校验数据的合法性;
            3.确认用户名是否被占用[SELECT接口];
              3.1 被占用,return返回结束;
              3.2 未被占用,插入数据[INSERT接口];
              3.3 返回响应.
         */
        log.debug("addUserDTO = {}", addUserDTO);
        User user = new User();
        BeanUtils.copyProperties(addUserDTO, user);
        user.setCreated(new Date());
        userMapper.insert(user);

        return JsonResult.ok();
    }

    /**
     * 2.查询用户列表
     */
    @GetMapping(value = "userList")
    @ApiOperation("查询用户列表")
    public JsonResult userList(){
        //梳理业务逻辑
        log.debug("addUserDTO ={}", userMapper.selectUserList());

        return JsonResult.ok(userMapper.selectUserList());
    }

    /**
     * 3.删除指定用户
     * @param id
     * @return
     */
    @GetMapping(value = "delete")
    @ApiOperation("删除指定用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int")
    public JsonResult deleteUser(Long id) throws Throwable {
        log.debug("id =" + id);
        if (id < 0 ){
            throw new Throwable("id不能小于0");
        }
        return JsonResult.ok();
    }


    /**
     * 4.修改用户信息
     * @param user
     * @return
     */
    @PostMapping(value = "update")
    @ApiOperation("修改用户信息")
    public JsonResult updateUser(User user){
        userMapper.update(user);
        return JsonResult.ok();
    }

    /**
     * 5.根据用户的id查询用户信息
     * http://localhost:8080/v1/users/8
     * @param id
     * @return
     */
    @ApiOperation("根据用户的id查询用户信息")
    @GetMapping(value ="{id}")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int")
    // 路径中的参数 是 id 方法接受的参数也是 id  @PathVariable就不用@PathVariable(value='id')
    public JsonResult getUserById(@PathVariable Long id){

        return JsonResult.ok(userMapper.getUserById(id));
    }
}
